package com.amex.SQL;

import java.io.Writer;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;

public class Utils {

	public static int parseInt(Object src, int defaultValue) {
		try {
			return Integer.parseInt(String.valueOf(src).trim());
		} catch (Throwable t) {
			return defaultValue;
		}
	}
	
	public static String trim(String source) {
		return trim (source, null);
	}
	/**
	 * return default value if source is null
	 * 
	 * @param source
	 * @param def
	 * @return
	 */
	public static String trim(String source, String def) {
		if (source == null) {
			return def;
		}
		return source.trim();
		
	}
	public static Timestamp parseTimestamp(String source) {
		return parseTimestamp(source, null, new Timestamp(System.currentTimeMillis()));
	}
	
	public static Timestamp parseTimestamp(String source, String format) {
		return parseTimestamp(source, format, new Timestamp(System.currentTimeMillis()));
	}
	
	public static Timestamp parseTimestamp(String source, String format, Timestamp def) {
		try {
			if(format == null) 
				format = "MM-dd-yyyy";
			SimpleDateFormat formatter = new SimpleDateFormat(format);
			Date d = formatter.parse(source);
			return (d == null) ? def : new Timestamp(d.getTime());
		} catch (Throwable t){
			return def;
		}
	}

	public static String toJSON(Object obj) {
		XStream x = new XStream(new JsonHierarchicalStreamDriver() {
			public HierarchicalStreamWriter createWriter(Writer out) {
				return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
			}
		});

		return (x.toXML(obj));
	}
	
	
//	public static String toJSON(Map src) {
//		XStream x = new XStream(new JsonHierarchicalStreamDriver() {
//			public HierarchicalStreamWriter createWriter(Writer out) {
//				return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
//			}
//		});
//
//		return (x.toXML(src));
//	}
}
